#!/usr/bin/python3
import glob
import requests

# 示例：下载《Pride and Prejudice》（傲慢与偏见） by Jane Austen 的文本版本
url = "https://www.gutenberg.org/files/1342/1342-0.txt"

def download(url, book):
    ret = False

    for file_name in glob.glob("*.txt"):
        if file_name == book:
            return True

    response = requests.get(url, book)
    if response.status_code == 200:
        with open(book, "w", encoding='utf-8') as f:
            f.write(response.text)
        print("下载完成，保存在 pride_and_prejudice.txt")
        ret = True
    else:
        print(f"下载失败，状态码: {response.status_code}")
        ret = False
    return ret

def count_string(file_name, key):
    with open(file_name) as file_object:
        context = file_object.read()
        num = context.lower().count(key)
        print(f"In {file_name}, the num of '{key}' is {num}")


ret = download(url, "pride_and_prejudice.txt")
if ret == True:
    count_string("pride_and_prejudice.txt","the")

